<template>
  <div class="boxes-detail-netwrok">
    <div class="network-config">
      <div class="title">
        <global-svg-icon
          icon-name="config-title-tri"
          width="3px"
          height="18px"
          style="vertical-align: middle"
        ></global-svg-icon>
        <span class="text">网络配置</span>
      </div>
      <a-spin :spinning="formLoading">
        <div class="config-info-box item">
          <div class="config-info">
            <a-form
              ref="configFormRef"
              :model="configForm"
              :rules="addRules"
              layout="vertical"
            >
              <div class="network-card-status">
                <p>{{ configForm.name }}</p>
                <div>
                  <global-svg-icon
                    v-if="configForm.status === 0"
                    icon-name="link-error"
                  ></global-svg-icon>
                  <global-svg-icon
                    v-else
                    icon-name="link-successful"
                  ></global-svg-icon>
                  <span>{{
                    configForm.status === 1 ? "连接正常" : "连接异常"
                  }}</span>
                </div>
              </div>
              <a-form-item name="networkType">
                <span class="dhcp-text">DHCP</span>
                <a-switch
                  :checked="configForm.networkType"
                  :disabled="configForm.status === 0"
                  @click="switchClick(1)"
                ></a-switch>
              </a-form-item>
              <a-form-item label="MAC地址" name="mac">
                <a-input
                  v-model:value.trim="configForm.mac"
                  disabled
                  placeholder="请输入MAC地址"
                  :maxlength="15"
                ></a-input>
              </a-form-item>
              <a-form-item label="IP地址" name="ip">
                <a-input
                  v-model:value.trim="configForm.ip"
                  :disabled="cFormItemDisbled(1)"
                  placeholder="请输入IP地址"
                  :maxlength="15"
                ></a-input>
              </a-form-item>
              <a-form-item label="IP子网掩码" name="cidr">
                <a-input
                  v-model:value.trim="configForm.cidr"
                  :disabled="cFormItemDisbled(1)"
                  placeholder="请输入IP子网掩码"
                  :maxlength="15"
                ></a-input>
              </a-form-item>
              <a-form-item label="IP默认网关" name="gateway">
                <a-input
                  v-model:value.trim="configForm.gateway"
                  placeholder="请输入IP默认网关"
                  :disabled="cFormItemDisbled(1)"
                  :maxlength="15"
                ></a-input>
              </a-form-item>
              <a-form-item label="dns" name="dns">
                <a-input
                  v-model:value.trim="configForm.dns"
                  :disabled="cFormItemDisbled(1)"
                  placeholder="请输入DNS"
                  :maxlength="15"
                ></a-input>
              </a-form-item>
            </a-form>
          </div>
          <!-- 网口2 -->
          <div class="config-info">
            <a-form
              ref="configFormRef2"
              :model="configForm2"
              :rules="addRules"
              layout="vertical"
            >
              <div class="network-card-status">
                <p>{{ configForm2.name }}</p>
                <div>
                  <global-svg-icon
                    v-if="configForm2.status === 0"
                    icon-name="link-error"
                  ></global-svg-icon>
                  <global-svg-icon
                    v-else
                    icon-name="link-successful"
                  ></global-svg-icon>
                  <span>{{
                    configForm2.status === 1 ? "连接正常" : "连接异常"
                  }}</span>
                </div>
              </div>
              <a-form-item name="networkType">
                <span class="dhcp-text">DHCP</span>
                <a-switch
                  :checked="configForm2.networkType"
                  :disabled="configForm2.status === 0"
                  @click="switchClick(2)"
                ></a-switch>
              </a-form-item>
              <a-form-item label="MAC地址" name="mac">
                <a-input
                  v-model:value.trim="configForm2.mac"
                  disabled
                  placeholder="请输入MAC地址"
                  :maxlength="15"
                ></a-input>
              </a-form-item>
              <a-form-item label="IP地址" name="ip">
                <a-input
                  v-model:value.trim="configForm2.ip"
                  :disabled="cFormItemDisbled(2)"
                  placeholder="请输入IP地址"
                  :maxlength="15"
                ></a-input>
              </a-form-item>
              <a-form-item label="IP子网掩码" name="cidr">
                <a-input
                  v-model:value.trim="configForm2.cidr"
                  :disabled="cFormItemDisbled(2)"
                  placeholder="请输入IP子网掩码"
                  :maxlength="15"
                ></a-input>
              </a-form-item>
              <a-form-item label="IP默认网关" name="gateway">
                <a-input
                  v-model:value.trim="configForm2.gateway"
                  placeholder="请输入IP默认网关"
                  :disabled="cFormItemDisbled(2)"
                  :maxlength="15"
                ></a-input>
              </a-form-item>
              <a-form-item label="dns" name="dns">
                <a-input
                  v-model:value.trim="configForm2.dns"
                  :disabled="cFormItemDisbled(2)"
                  placeholder="请输入DNS"
                  :maxlength="15"
                ></a-input>
              </a-form-item>
            </a-form>
          </div>
        </div>
        <a-button
          v-if="
            g6Permission.showBtn('network-edit') &&
            (!configForm.networkType || !configForm2.networkType)
          "
          class="save-btn"
          type="primary"
          :loading="loading"
          @click="saveConfig"
          >保存</a-button
        >
      </a-spin>
    </div>
    <div class="server-information">
      <div class="title">
        <global-svg-icon
          icon-name="config-title-tri"
          width="3px"
          height="18px"
          style="vertical-align: middle"
        ></global-svg-icon>
        <span class="text">SIP服务器信息</span>
      </div>
      <div class="server-info item">
        <div class="server-item">
          <div class="label">ID</div>
          <div class="value">{{ boxSipInfo.id }}</div>
        </div>
        <div class="server-item">
          <div class="label">域</div>
          <div class="value">{{ boxSipInfo.domain }}</div>
        </div>
        <div class="server-item">
          <div class="label">地址</div>
          <div class="value">{{ boxSipInfo.ip }}</div>
        </div>
        <div class="server-item">
          <div class="label">端口</div>
          <div class="value">{{ boxSipInfo.port }}</div>
        </div>
      </div>
    </div>
  </div>

  <a-modal
    v-model:open="dhcpTipVisible"
    :title="'提示'"
    @ok="confirmChangeDHCP"
    :centered="true"
    width="416px"
  >
    <div class="dhcp-tip">
      <i class="iconfont icon-information-fill"></i>
      <div class="info-text">
        <p>
          点击确认后，新设置将立即生效。请注意，之后您需要使用更新的IP地址来访问本系统。为确保顺畅访问，请务必妥善记录新配置信息。
        </p>
        <div class="info-guide">
          <a-tooltip :overlayInnerStyle="{ width: '368px !important' }">
            <span>DHCP配置与IP地址查看指南</span>
            <template #title>
              <div class="guide-tooltip">
                <p>1、开启DHCP时请通过渠道扫描工具扫描/连接显示器方式査看IP</p>
                <p>2、选择手动输入时请记录对应IP信息/连接显示器方式查看IP</p>
                <p>3、关闭DHCP但未进行任何编辑时，系统会默认之前使用的IP地址</p>
              </div>
            </template>
            <i class="iconfont icon-question-line"></i>
          </a-tooltip>
        </div>
      </div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { createVNode } from "vue";
import { Rule } from "ant-design-vue/es/form";
import { ipReg, cidrReg } from "@/global-utils/check";
import { FormInstance, message, Modal } from "ant-design-vue";
import { g6Permission, g6DeepClone } from "glasssix-utils-ts";
import { BoxManageApi } from "../../../api";
import { confirm } from "@/global-utils/antd.util";

defineOptions({ name: "BoxNetwrok" });
const route = useRoute();
const boxSerials = ref<any>("");
boxSerials.value = route.query.boxSerial;
// 网络配置表单
const configFormRef = ref<FormInstance>();
const configFormRef2 = ref<FormInstance>();

// 表单禁用
const cFormItemDisbled = computed(() => {
  return (lanType: number) => {
    if (lanType === 1) {
      return !g6Permission.showBtn("network-edit") || configForm.networkType;
    }
    return !g6Permission.showBtn("network-edit") || configForm2.networkType;
  };
});

interface ConfigForm {
  name: string | undefined;
  mac: string;
  ip: string;
  cidr: string;
  gateway: string;
  dns: string;
  boxSerial: string;
  status: number;
  networkType: boolean;
}

let configForm = reactive<ConfigForm>({
  name: undefined,
  mac: "",
  ip: "",
  cidr: "",
  gateway: "",
  dns: "",
  boxSerial: "",
  status: 0,
  networkType: false,
});
let configForm2 = reactive<ConfigForm>({
  name: undefined,
  mac: "",
  ip: "",
  cidr: "",
  gateway: "",
  dns: "",
  boxSerial: "",
  status: 0,
  networkType: false,
});
const formLoading = ref<boolean>(false);
const id = ref<string>("");
const boxSerial = ref<string>("");
// 盒子名称
const name = ref<string>("");
const networkGetByBoxSerial = async (): Promise<void> => {
  formLoading.value = true;
  const param = {
    boxSerial: boxSerial.value,
  };
  const { data } = await BoxManageApi.networkGetByBoxSerial(param);
  if (data) {
    Object.assign(configForm, data[0]);
    Object.assign(configForm2, data[1]);
    configForm.networkType = data[0].networkType === "manual" ? false : true;
    configForm2.networkType = data[1].networkType === "manual" ? false : true;
  } else {
    message.warning("网络配置获取失败");
  }
  formLoading.value = false;
};
// 表格正则
const addRules: Record<string, Rule[]> = {
  ip: [
    { required: true, message: "请输入ip地址", trigger: "blur" },
    {
      pattern: ipReg,
      message: "请输入正确的IP地址，其中每个数字的范围为0-255",
      trigger: "blur",
    },
  ],
  mac: [{ required: true, message: "mac地址不能为空" }],
  name: [{ required: true, message: "网卡不能为空" }],
  cidr: [
    { required: true, message: "请输入IP子网掩码", trigger: "blur" },
    {
      pattern: cidrReg,
      message: "请输入正确的IP子网掩码，其中每个数字的范围为0-255",
      trigger: "blur",
    },
  ],
  gateway: [
    { required: true, message: "请输入IP默认网关", trigger: "blur" },
    {
      pattern: ipReg,
      message: "请输入正确的IP默认网关，其中每个数字的范围为0-255",
      trigger: "blur",
    },
  ],
  dns: [
    { required: true, message: "请输入DNS", trigger: "blur" },
    {
      pattern: ipReg,
      message: "请输入正确的DNS，其中每个数字的范围为0-255",
      trigger: "blur",
    },
  ],
};

// dhcp Switch
const dhcpTipVisible = ref(false);
const dhcpTipType = ref<number>(1);
const switchClick = (type: 1 | 2) => {
  dhcpTipVisible.value = true;
  dhcpTipType.value = type;
};

const confirmChangeDHCP = async () => {
  let dhcpStatus = false;
  if (dhcpTipType.value === 1) {
    configForm.networkType = !configForm.networkType;
    dhcpStatus = configForm.networkType;
  }
  if (dhcpTipType.value === 2) {
    configForm2.networkType = !configForm2.networkType;
    dhcpStatus = configForm2.networkType;
  }
  dhcpChange(dhcpStatus, dhcpTipType.value);
  dhcpTipVisible.value = false;
};

const dhcpChange = async (checked: boolean, type: number) => {
  if (!checked) {
    return;
  }
  formLoading.value = true;
  try {
    let param = g6DeepClone(type === 1 ? configForm : configForm2);
    param.networkType = param.networkType ? "auto" : "manual";
    await BoxManageApi.saveBoxNetConfigService([param]);
    let { data } = await BoxManageApi.networkGetByBoxSerial({
      boxSerial: boxSerial.value,
    });
    if (data) {
      if (type === 1) {
        Object.assign(configForm, { ...data[0] });
        configForm.networkType =
          data[0].networkType === "manual" ? false : true;
      } else {
        Object.assign(configForm2, { ...data[1] });
        configForm2.networkType =
          data[1].networkType === "manual" ? false : true;
      }
    }
    formLoading.value = false;
    message.success("操作成功");
  } catch (error) {
    formLoading.value = false;
  }
};

// sip服务器信息
const boxSipInfo = ref<Record<string, string>>({
  id: "",
  sipId: "",
  domain: "",
  ip: "",
  port: "",
});
// 获取
const getBoxSipInfo = async (): Promise<void> => {
  const { data } = await BoxManageApi.getBoxSipInfo(boxSerial.value);
  boxSipInfo.value = { ...data };
};

const loading = ref<boolean>(false);

const formValidate = async () => {
  const validationPromises = [
    configForm.status === 1 && configFormRef.value?.validate(),
    configForm2.status === 1 && configFormRef2.value?.validate(),
  ];
  // 并行执行所有验证操作
  await Promise.all(validationPromises);
};
// 保存
const saveConfig = async (): Promise<void> => {
  loading.value = true;
  try {
    await formValidate();
    let data = g6DeepClone([configForm, configForm2]);
    data[0].networkType = data[0].networkType ? "auto" : "manual";
    data[1].networkType = data[1].networkType ? "auto" : "manual";
    let res: TsRes = await BoxManageApi.saveBoxNetConfigService(data);
    if (res.code === 0) {
      message.success("操作成功");
    }
    loading.value = false;
  } catch (error) {
    loading.value = false;
    console.error(error);
  }
};

onMounted(() => {
  id.value = route.query?.id as string;
  boxSerial.value = route.query?.boxSerial as string;
  name.value = route.query?.name as string;
  getBoxSipInfo();
  networkGetByBoxSerial();
});
</script>
<style lang="less" scoped>
.guide-tooltip {
  font-size: 12px;
  color: @text02;
}
.dhcp-tip {
  padding: 24px 32px;
  padding-bottom: 0;
  display: flex;
  gap: 16px;
  .icon-information-fill {
    color: rgba(0, 156, 248, 1);
    font-size: 24px;
  }
  .info-text {
    color: @text01;
    line-height: 22px;
  }
  .info-guide {
    margin-top: 16px;
    color: #8599bf;
    font-size: 12px;
    display: flex;
    align-items: center;
    cursor: default;
    .icon-question-line {
      margin-left: 8px;
      font-size: 14px;
    }
  }
}
.boxes-detail-netwrok {
  display: flex;
  justify-content: center;

  .title {
    margin-bottom: 16px;

    .text {
      display: inline-block;
      margin-left: 8px;
      font-size: 16px;
      font-weight: 700;
      line-height: 24px;
      color: @text01;
    }
  }

  .network-card-status {
    display: flex;
    margin-bottom: 32px;
    font-size: 14px;
    color: #fff;

    > p {
      margin-right: 8px;
      font-family: "Noto Sans SC";
      font-size: 16px;
      font-weight: 700;
      font-style: normal;
    }

    span {
      margin-left: 2px;
      color: @text03;
    }
  }

  .item {
    border: 1px solid @borderColor02;
    border-radius: 4px;
    padding: 20px;
    background: @background02;
    box-shadow: 0 40px 180px 0 rgba(0, 0, 0, 0.35);
  }

  .network-config {
    width: 720px;
    height: 844px;
    margin-right: 80px;
    margin-bottom: 40px;

    .dhcp-text {
      margin-right: 8px;
      font-size: 14px;
      vertical-align: -2px;
      color: #fff;
    }

    .save-btn {
      position: relative;
      top: -60px;
      left: 20px;
    }

    .config-info-box {
      display: flex;
      width: 720px;
      align-items: center;
      gap: 0 40px;
      padding-bottom: 60px;
    }

    .config-info {
      width: 320px;
      // 禁用项背景色
      .ant-input-disabled {
        background: @mask02 !important;
      }

      .ant-form-item {
        margin-bottom: 32px;
      }

      :deep(.ant-form-item-explain) {
        bottom: auto !important;
      }

      .ant-form-item-control-input {
        input {
          height: 38px !important;
        }
      }

      .ant-btn {
        // width: 60px !important;
        min-width: 60px !important;
        height: 36px !important;
      }
    }
  }

  .server-information {
    width: 360px;
    height: 368px;

    .server-info {
      height: 328px;
      padding: 12px 20px;
      background: #101b2f;

      .server-item {
        border-bottom: 1px solid @borderColor02;
        padding: 12px 0;
        line-height: 22px;

        .label {
          margin-bottom: 8px;
          line-height: 22px;
          color: @text03;
        }

        .value {
          color: @text01;
        }
      }

      .server-item:last-child {
        border-bottom: none;
      }
    }
  }
}
</style>
